<template>
  <div class="role-wrapper">
    <!-- 搜索框 -->
    <Form :model="formRight" label-position="right" :label-width="80">
      <Row :gutter="10">
        <Col :xs="24" :sm="24" :md="12" :lg="6">
          <FormItem label="角色：">
            <Input v-model="formRight.roleName" placeholder="请输入角色名称"></Input>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="12" :lg="6">
          <FormItem>
            <Button type="primary" @click="queryRole" shape="circle" icon="ios-search">查询</Button>
          </FormItem>
        </Col>
      </Row>
    </Form>

    <!-- 工具栏 -->
    <div class="tool-box">
      <Button type="primary" icon="md-add" ghost @click="addRoleModel = true">添加角色</Button>
      <Button type="error" icon="md-trash" ghost style="margin-left:10px;">批量删除</Button>
    </div>

    <!-- 表格数据 -->
    <Table :loading="loading" border ref="selection" :columns="columns" :data="tableData"></Table>
    <!-- 分页按钮 -->
    <div class="page-wrapper">
      <Page :total="total" @on-change="handlePage" show-elevator show-total/>
    </div>

    <!-- 添加角色 -->
    <div class="add-role">
      <Modal
        v-model="addRoleModel"
        title="添加角色"
        @on-ok="handelAddRole"
        @on-cancel="cancelRoleAdd"
      >
        <Form ref="formInline" :model="formData" :rules="ruleInline">
          <Row :gutter="10">
            <Col span="24">
              <FormItem label="角色" prop="roleName" label-position="top">
                  <Input v-model="formData.roleName" placeholder="请输入角色，必填" />
              </FormItem>
            </Col>
            <Col span="24">
              <FormItem label="说明" prop="note" label-position="top">
                  <Input v-model="formData.note" placeholder="请输入说明" />
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>

    <!-- 修改角色 -->
    <div class="edit-role">
      <Modal
        v-model="editRoleModel"
        title="修改角色"
        @on-ok="handelEditRole"
        @on-cancel="cancelRoleEdit"
      >
        <Form ref="formInlineEdit" :model="formDataEdit" :rules="ruleInlineEdit">
          <Row :gutter="10">
            <Col span="24">
              <FormItem label="角色" prop="roleName" label-position="top">
                  <Input v-model="formDataEdit.roleName" placeholder="请输入角色，必填" />
              </FormItem>
            </Col>
            <Col span="24">
              <FormItem label="说明" prop="note" label-position="top">
                  <Input v-model="formDataEdit.note" placeholder="请输入说明" />
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>

    <!-- 分配菜单权限 -->
    <div class="role-menu">
      <Modal
        v-model="roleMenuModel"
        :title="roleMenuTitle"
        @on-ok="handelRoleMenu"
        @on-cancel="clearMenuData"
      >
        <div style="max-height:650px; overflow: auto">
          <Tree ref="tree" :data="menuData" show-checkbox expand-node multiple :check-strictly="true"></Tree>
        </div>
      </Modal>
    </div>

    <!-- 分配功能权限 -->
    <div>
      <Modal
        v-model="permissionModel"
        :title="permissionTitle"
        @on-ok="handelPermission"
        @on-cancel="cancelPermission"
        width="600"
      >
        <div style="max-height:650px; overflow: auto; max-width: 600px">
          <Transfer
            :data="permissionData"
            :target-keys="targetKeys"
            :render-format="render"
            @on-change="handleChange"
            :titles="titles"
            :list-style="listStyle"
          >
          </Transfer>
        </div>
      </Modal>
    </div>
  </div>
</template>

<script>
import {
  queryRolePage,checkRole,addRole,updateRole,deleteRole,getRoleMenuData,setRoleMenu,
  getPermissionIds,setRolePermission
} from '@/api/role'

import {getAllPermission} from '@/api/permission'

export default {
  name: 'Role',
  data(){
    /**
     * 校验角色是否已存在
     */
    const validateRoleName = (rule, value, callback) => {
      if(value && value.trim() != ''){
        checkRole({roleName: value}).then(res => {
          if(res.data.status){
            callback()
          }else{
            callback(new Error(res.data.msg))
          }
        })
      }else{
        callback()
      }
    }

    return {
      formRight: {
        roleName: ''
      },
      tableData: [],
      total: 0,
      loading: true,
      columns: [
        {
          type: 'selection',
          align: 'center',
          width: 60,
          fixed: 'left'
        },
        {
          type: 'index',
          width: 60,
          align: 'center'
        },
        {
          title: '角色',
          key: 'roleName',
          minWidth: 150
        },
        {
          title: '角色描述',
          key: 'note',
          minWidth: 150
        },
        {
          title: '创建时间',
          key: 'createTime',
          minWidth: 170
        },
        {
          title: '更新时间',
          key: 'updateTime',
          minWidth: 170
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 280,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'text',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.permissionModel = true
                    this.permissionTitle = '分配 [ '+ params.row.roleName + ' ] 的功能权限'
                    getAllPermission().then(res => {
                      if(res.data.status){
                        this.permissionData = res.data.data
                      }
                    })
                    this.currentRoleId = params.row.id
                    getPermissionIds(params.row.id).then(res => {
                      if(res.data.status){
                        this.targetKeys = res.data.data
                      }
                    })
                  }
                }
              }, '功能权限'),
              h('Button', {
                props: {
                  type: 'text',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.roleMenuModel = true
                    this.roleMenuTitle = '分配 [ '+ params.row.roleName + ' ] 的菜单权限'
                    this.queryRoleMenuData(params.row.id)
                    this.currentRoleId = params.row.id
                  }
                }
              }, '菜单权限'),
              h('Button', {
                props: {
                  type: 'text',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.editRoleModel = true
                    this.formDataEdit = {...params.row}
                  }
                }
              }, '修改'),
              h('Button', {
                props: {
                  type: 'text',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '删除角色',
                      content: '您确认要删除角色：<strong>'+params.row.roleName+'</strong>?',
                      onOk: () => {
                        deleteRole(params.row.id).then(res =>{
                          if(res.data.status){
                            this.$Message.success('删除成功')
                            this.tableData.forEach((item,index, arr) => {
                              if(item.id === params.row.id){
                                arr.splice(index, 1)
                                this.total = this.total - 1
                              }
                            })
                          }
                        })
                      }
                    })
                  }
                }
              }, '删除')
            ]);
          }
        }
      ],
      addRoleModel: false,
      formData: {
        roleName: '',
        note: ''
      },
      ruleInline: {
        roleName: [
          { required: true, message: '角色不能为空'},
          { validator: validateRoleName, trigger: 'blur' }
        ]
      },
      editRoleModel: false,
      formDataEdit: {
        roleName: '',
        note: ''
      },
      ruleInlineEdit: {
        roleName: [
          { required: true, message: '角色不能为空'}
        ]
      },
      roleMenuTitle: '',
      roleMenuModel: false,
      menuData:[],
      currentRoleId: '',
      permissionModel: false,
      permissionTitle: '',
      permissionData: [],
      targetKeys: [],
      titles: ['未拥有权限','已拥有权限'],
      listStyle:{
        width: '250px',
        minHeight: '300px'
      }
    }
  },
  methods:{
    /**
     * 查询角色
     */
    queryRole(){
      this.loading = true
      queryRolePage({
        pageSize: 10,
        pageNum: 1,
        roleName: this.formRight.roleName
      }).then(res => {
        this.loading = false
        if(res.data.status){
          this.tableData = res.data.data.list == null ? [] : res.data.data.list
          this.total = res.data.data.total
        }
      }).catch(()=>{
        this.loading = false
      })
    },
    /**
     * 分页处理
     */
    handlePage(pageNum){
      this.loading = true
      queryRolePage({
        pageSize: 10,
        pageNum: pageNum,
        roleName: this.formRight.roleName
      }).then(res => {
        this.loading = false
        if(res.data.status){
          this.tableData = res.data.data.list == null ? [] : res.data.data.list
          this.total = res.data.data.total
        }
      }).catch(()=>{
        this.loading = false
      })
    },
    /**
     * 添加角色
     */
    handelAddRole(){
      this.$refs['formInline'].validate((valid) => {
        if(valid){
          addRole({
            roleName: this.formData.roleName,
            note: this.formData.note
          }).then(res => {
            if(res.data.status){
              this.queryRole()
              this.$Message.success({content: '添加角色成功'})
              this.formData.roleName = ''
              this.formData.note = ''
            }
          })
        }
      })
    },
    /**
     * 修改角色
     */
    handelEditRole(){
      this.$refs['formInlineEdit'].validate((valid) => {
        if(valid){
          updateRole({
            roleId: this.formDataEdit.id,
            roleName: this.formDataEdit.roleName,
            note: this.formDataEdit.note
          }).then(res => {
            if(res.data.status){
              const result = res.data.data
              let resultArr = []
              this.tableData.forEach((item,index,arr) => {
                if(item.id === result.id){
                  resultArr[index] = result
                }else{
                  resultArr[index] = item
                }
              })
              this.tableData = resultArr
              this.editRoleModel = false
              this.$Message.success({
                content: '修改角色成功'
              })
            }
          })
        }
      })
    },
    /**
     * 分配菜单权限
     */
    handelRoleMenu(){
      //console.log(this.$refs.tree.getCheckedAndIndeterminateNodes())
      if(this.menuData && this.menuData.length > 0){
        let menuIds = []
        this.$refs.tree.getCheckedAndIndeterminateNodes().forEach(item => {
          menuIds.push(item.id)
        })
        setRoleMenu({roleId: this.currentRoleId, menuIds: menuIds}).then(res => {
          if(res.data.status){
            this.$Message.success("菜单权限分配成功")
          }
        })
      }else{
        this.$Message.warning("菜单数据异常！")
      }
    },
    /**
     * 获取角色菜单数据
     */
    queryRoleMenuData(roleId){
      getRoleMenuData(roleId).then(res => {
        if(res.data.status){
          this.menuData = res.data.data
        }
      })
    },
    /**
     * 清除角色菜单数据
     */
    clearMenuData(){
      this.menuData = []
    },
    /**
     * 保存功能权限
     */
    handelPermission(){
      if(this.currentRoleId && this.currentRoleId.length > 0){
        let data = {
          roleId: this.currentRoleId,
          permissionIds: this.targetKeys
        }
        setRolePermission(data).then(res => {
          if(res.data.status){
            this.$Message.success('保存成功')
            this.permissionModel = false
            this.currentRoleId = ''
          }
        })
      }else{
        this.$Message.error('数据异常')
      }
    },
    /**
     * 添加角色界面关闭
     */
    cancelRoleAdd(){
      this.$refs.formInline.resetFields()
    },
    cancelRoleEdit(){
      this.$refs.formInlineEdit.resetFields()
    },
    cancelPermission(){

    },
    /**
     * 功能权限渲染
     */
    render(item){
      return item.note == '' ? item.name : item.note
    },
    handleChange(newTargetKeys){
      this.targetKeys = newTargetKeys
    }
  },
  created(){
    // 初始化角色列表数据
    this.queryRole()
  }
}
</script>

<style lang="less">
.role-wrapper{
  padding: 10px;
  .tool-box{
    padding: 10px;
    padding-left: 0;
  }
  .page-wrapper{
    padding-top: 10px;
    padding-bottom: 10px;
  }
  .role-menu{
    width: 100%;
    height: 100%;
  }
}
</style>
